<?php
/**
 * @title 96. 不同的二叉搜索树 - 迭代
 * @author start2004
 */

class Solution {

    /**
     * @param Integer $n
     * @return Integer
     */
    function numTrees($n) {
        /**
         * @since 2020-07-15 避免重复计算
         */
        $dpArray = [
            0 => 1,
            1 => 1,
            2 => 2,
        ];

        /**
         * @since 2020-07-15 迭代计算
         */
        for ($i=3; $i<=$n; $i++){
            $sum = 0;

            /**
             * @since 2020-08-13 对半累加
             */
            $left = 0;
            $right = $i-1;
            while($left<$right){
                $sum += ($dpArray[$left] * $dpArray[$right])<<1;
                $left++;
                $right--;
            }

            /**
             * @since 2020-08-13 left=right, 补中间点
             */
            if($left == $right){
                $sum += $dpArray[$left]*$dpArray[$left];
            } else {}
            $dpArray[$i] = $sum;
        }

        /**
         * @return
         */
        return $dpArray[$n];
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.15_3.php
 */
$datas = [
    3,
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->numTrees($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
